const router = require('koa-router')()
const tools = require('../../model/tools')
const svgCaptcha = require('svg-captcha')

let Admin = require('../../models/Admin')

router.get('/', async (ctx) => {
  await ctx.render('admin/login')
})

router.post('/doLogin', async (ctx) => {

  let {username, password, code} = ctx.request.body

  if (code.toLocaleLowerCase() === ctx.session.code.toLocaleLowerCase()) {
    password = tools.md5(password)
    let result = await Admin.findOne({
      username,
      password
    })
      .then(async (result) => {
      if (result) {
        ctx.session.userinfo = result
        ctx.redirect(`${ctx.state.__HOST__}/admin`)
        await Admin.findByIdAndUpdate(result._id, {
          last_time: new Date()
        }).then(updateResult => {
          console.log(updateResult)
          if (updateResult) {
            console.log('最后登录时间保存成功')
          }
        })
      } else {
        await ctx.render('admin/error', {
          message: '用户名或者密码错误',
          redirect: `${ctx.state.__HOST__}/admin/login`
        })
      }
    })
  } else {
    ctx.render('admin/error', {
      message: '验证码失败',
      redirect: `${ctx.state.__HOST__}/admin/login`
    })
  }

})

router.get('/code', async (ctx) => {
  let captcha = svgCaptcha.create({
    size: 4,
    fontSize: 50,
    width: 120,
    height: 34,
    background: '#cc9966'
  })
  /*//加法验证码
  let captcha = svgCaptcha.createMathExpr({
    size: 4,
    fontSize: 50,
    width: 100,
    height: 40,
    background: '#cc9966'
  })*/
  //console.log(captcha.text)
  //保存生成的验证码
  ctx.session.code = captcha.text
  //返回验证码
  ctx.response.type = 'image/svg+xml'
  ctx.body = captcha.data
})

router.get('/loginOut', async (ctx) => {
  ctx.session.userinfo = null
  ctx.redirect(`${ctx.state.__HOST__}/admin/login`)
})




module.exports = router.routes()